# ------------------------------------------------------------------------------------------------
### Generate Table 9: Effects by alternative estimator
# ------------------------------------------------------------------------------------------------

# Load required data
load("../data/processed/LGBTQ_election_data.Rda")

# Exclude Warsaw for all subsequent analyses
LGBTQ_election_data <- LGBTQ_election_data %>%
  filter(id_county != 1465)

# Create cutoff sample
LGBTQ_election_data_cutoff <- create_cutoff_sample(LGBTQ_election_data)

# Set seed for reproducibility
set.seed(7361)

# Define estimators and outcome variables
estimators <- list(did = did_estimate, mc = mc_estimate, sdid = synthdid_estimate)
outcome_vars <- list(
  "Overall Turnout" = "turnout",
  "Opposition Turnout" = "non_pis_support", 
  "Government Turnout" = "pis_support"
)

# Function to estimate results for all estimators
estimate_effects <- function(data, var) {
  sc_did <- data %>% select(id, eyear, all_of(var), treat)
  setup <- panel.matrices(as.data.frame(as_tibble(sc_did)))
  
  estimates <- map(estimators, ~ .x(setup$Y, setup$N0, setup$T0))
  ste <- map2_dbl(estimates, names(estimators), ~ {
    if (.y == "mc") mc_placebo_se(setup$Y, setup$N0, setup$T0)
    else sqrt(vcov(.x, method = "placebo"))
  })
  
  return(rbind(unlist(estimates), ste))
}

# Compute estimates for each outcome in both samples
full_sample_results <- map(outcome_vars, ~ estimate_effects(LGBTQ_election_data, .x))
cutoff_results <- map(outcome_vars, ~ estimate_effects(LGBTQ_election_data_cutoff, .x))

# Generate LaTeX table
generate_latex_table <- function(full_results, cutoff_results, party_names) {
  # Create combined table
  n_outcomes <- length(party_names)
  combined_table <- matrix(nrow = 4 * n_outcomes, ncol = ncol(full_results[[1]]))
  colnames(combined_table) <- colnames(full_results[[1]])
  
  # Fill table with results
  for (i in seq_along(full_results)) {
    idx <- 4 * i - 3
    combined_table[idx:(idx+3), ] <- rbind(
      full_results[[i]][1, ], full_results[[i]][2, ],
      cutoff_results[[i]][1, ], cutoff_results[[i]][2, ]
    )
  }
  
  # Format results
  combined_table <- round(combined_table, 2)
  combined_table[seq(2, nrow(combined_table), 4), ] <- paste0("(", combined_table[seq(2, nrow(combined_table), 4), ], ")")
  combined_table[seq(4, nrow(combined_table), 4), ] <- paste0("(", combined_table[seq(4, nrow(combined_table), 4), ], ")")
  
  # Generate LaTeX
  latex_parts <- c(
    "\\begin{table}[ht]",
    "\\centering", 
    "\\begin{tabular}{l l ccc}",
    "\\hline\\hline",
    "\\addlinespace",
    "Outcome & Sample & DiD & MC & sDiD \\\\",
    "\\hline",
    "\\addlinespace"
  )
  
  # Add table rows
  for (i in seq(1, nrow(combined_table), 4)) {
    outcome_name <- party_names[ceiling(i/4)]
    latex_parts <- c(latex_parts,
      paste0(outcome_name, " & Full Sample & ", paste(combined_table[i, ], collapse = " & "), " \\\\"),
      paste0(" & & ", paste(combined_table[i + 1, ], collapse = " & "), " \\\\"),
      paste0(" & $<$ 50km Sample & ", paste(combined_table[i + 2, ], collapse = " & "), " \\\\"),
      paste0(" & & ", paste(combined_table[i + 3, ], collapse = " & "), " \\\\")
    )
    if (i < (nrow(combined_table) - 3)) latex_parts <- c(latex_parts, "\\addlinespace")
  }
  
  # Close table
  latex_parts <- c(latex_parts,
    "\\addlinespace",
    "\\hline",
    "\\end{tabular}",
    "\\caption{Comparison of Estimators for Overall, Opposition, and Government Turnout}",
    "\\label{tab:by_estimator}",
    "\\end{table}"
  )
  
  return(paste(latex_parts, collapse = "\n"))
}

# Generate and save table
latex_table <- generate_latex_table(full_sample_results, cutoff_results, names(outcome_vars))
writeLines(latex_table, "../output/tables/table9.txt")
